package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableRiskTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagRiskTag {
    public long uid;
    public int is_diversion;

    public static Logger LOG = LoggerFactory.getLogger(TagRiskTag.class);

    public TagRiskTag() {}

    public static TagRiskTag init(long uid, int isDiversion) {
        return new TagRiskTag(uid, isDiversion);
    }

    public TagRiskTag(long uid, int isDevisioned) {
        this.uid = uid;
        this.is_diversion = isDevisioned;
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableRiskTag.QUERYSQL);
        DataStream<Tuple2<Boolean, TableRiskTag>> inputStream =
                tableEnv.toRetractStream(tableRes, TableRiskTag.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableRiskTag>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableRiskTag> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagRiskTag-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableRiskTag>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableRiskTag> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<Tuple2<Boolean, TableRiskTag>, String>() {
                                    ValueState<TagRiskTag> riskTagVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        riskTagVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagRiskTag>(
                                                                        "riskTagVState",
                                                                        TagRiskTag.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableRiskTag> value,
                                            Collector<String> out)
                                            throws Exception {
                                        if (value.f1.getType().equals("DIVERSION")) {
                                            long uid = value.f1.getUid();
                                            TagRiskTag tmpTagRiskTag = riskTagVState.value();
                                            TagRiskTag curRisktag =
                                                    tmpTagRiskTag == null
                                                            ? TagRiskTag.init(uid, -1)
                                                            : tmpTagRiskTag;
                                            JSONObject jsonObject = new JSONObject();

                                            try {
                                                int is_diversion =
                                                        Integer.parseInt(value.f1.getVal());

                                                if (curRisktag.getIs_diversion() != is_diversion) {
                                                    curRisktag.is_diversion = is_diversion;
                                                    jsonObject.put("uid", uid);
                                                    jsonObject.put("is_diversion", is_diversion);
                                                    out.collect(jsonObject.toString());
                                                    riskTagVState.update(curRisktag);
                                                }
                                            } catch (Exception E) {
                                                LOG.error(E.getMessage());
                                            }
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getIs_diversion() {
        return is_diversion;
    }

    @Override
    public String toString() {
        return "RiskTag{" + "uid=" + uid + ", is_diversion=" + is_diversion + '}';
    }
}
